﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;

namespace Sern.Common
{
    public static class ComponentLocator
    {
        private static IUnityContainer _container;

        /// <summary>
        /// Find and run all the local registrar.
        /// </summary>
        static ComponentLocator()
        {
            var unityContainer = new UnityContainer();

            new FileInfo(Assembly.GetExecutingAssembly().Location)
                .Directory
                .GetFiles("Sern*.dll")
                .Select(
                    file => Assembly.LoadFile(file.FullName).GetTypes())
                .SelectMany(type => type)
                .Where(type => 
                    type.Namespace != null 
                    && !type.Namespace.StartsWith("Sern.Common")
                    && typeof(IComponentRegistrar).IsAssignableFrom(type))
                .ToList()
                .ForEach(registrar => 
                    (Activator.CreateInstance(registrar) as IComponentRegistrar)
                    .Register(unityContainer));

            _container = unityContainer;
        }
        
        /// <summary>
        /// Serve up Unity to Any requestor.
        /// </summary>
        public static IUnityContainer Unity
        {
            get { return _container; }
        }

        public static void Reset()
        {
            _container = new UnityContainer();
        }
    }
}
